package org.xs.object.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.xs.object.dao.user.UserRepository;

import java.io.InputStream;

@Component
@PropertySource("classpath:OssUserFile.properties")
public class AilOssUtil {
    private final   String ACCESS_KEY_ID;
    private final   String ACCESS_KEY_SECRET;
    private final   String ENDPOINT;
    private final   String BUCKET_NAME;
    private final   String REGION;
    private UserRepository userRepository;

    public AilOssUtil(
            @Value("${ACCESS.KEY.ID}")
            String accessKeyId,
            @Value("${ACCESS.KEY.SECRET}")
            String accessKeySecret,
            @Value("${ENDPOINT}")
            String endpoint,
            @Value("${BUCKET_NAME}")
            String bucketName,
            @Value("${REGION}")
            String region,
            UserRepository userRepository) {
        ACCESS_KEY_ID = accessKeyId;
        ACCESS_KEY_SECRET = accessKeySecret;
        ENDPOINT = endpoint;
        BUCKET_NAME = bucketName;
        REGION = region;
        this.userRepository = userRepository;
    }

    private OSS ossClient(){
        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(ENDPOINT)
                //.credentialsProvider(credentialsProvider)
                .credentialsProvider(new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET))
                .clientConfiguration(clientBuilderConfiguration)
                .region(REGION)
                .build();
        return ossClient;
    };
    public String upLoadFile(String ObjectName, InputStream in) throws com.aliyuncs.exceptions.ClientException {
        //调用方法的创建OSS实例。
        OSS ossClient = ossClient();
        String url="";
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    BUCKET_NAME,
                    ObjectName ,
                    in);

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("image/jpeg");
            putObjectRequest.setMetadata(metadata);
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            // 获取上传文件的URL。
            url="https://" + BUCKET_NAME + "." + ENDPOINT.substring(ENDPOINT.indexOf("://") + 3) + "/" + ObjectName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
    //删除头像
    public Boolean deleteAvatarFile() {
        //通过用户ID获取用户头像
        Integer userId= Integer.valueOf(ThreadLocatUtil.get());
        String avatarAddress=userRepository.findByUserPic(userId);
        //https://big-event-box.oss-cn-beijing.aliyuncs.com/3e596437-b598-4128-acc8-81517aba0153.png
        if (avatarAddress==null){
            return true;
        }
        //截取字符串
        String ObjectName=avatarAddress.substring(avatarAddress.indexOf("shang-gui-gu.oss-cn-hangzhou.aliyuncs.com/")+"shang-gui-gu.oss-cn-hangzhou.aliyuncs.com/".length());
        OSS ossClient = ossClient();
        try {
            // 删除文件。
            ossClient.deleteObject(BUCKET_NAME, ObjectName);
            return true;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            return false;
        }
    }
}
